//
//  GrowlInterface.m
//  Pennyworth
//
//  Created by Chris Karr on 12/31/07.
//  Copyright 2007 Chris J. Karr. All rights reserved.
//

#import "GrowlInterface.h"
#import "Learner.h"

#define ACTIVITY_UPDATE @"Activity Update"
#define LOCATION_UPDATE @"Location Update"
#define SOCIAL_UPDATE @"Social Context Update"
#define CONTEXT_UPDATE @"Context Update"

#define DO_GROWL @"Growl"

@implementation GrowlInterface

- (void) awakeFromNib
{
	cache = [[NSMutableDictionary alloc] init];
	
	[GrowlApplicationBridge setGrowlDelegate:self];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processPrediction:) name:PREDICTION_FETCHED object:nil];
}

- (NSDictionary *) registrationDictionaryForGrowl
{
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	
	NSArray * growls = [NSArray arrayWithObjects:CONTEXT_UPDATE, ACTIVITY_UPDATE, LOCATION_UPDATE, SOCIAL_UPDATE, nil];
	
	[dict setValue:growls forKey:GROWL_NOTIFICATIONS_ALL];
	[dict setValue:growls forKey:GROWL_NOTIFICATIONS_DEFAULT];
	
	return dict;
}

- (void) processPrediction:(NSNotification *) note
{
	NSNumber * doGrowl = [[NSUserDefaults standardUserDefaults] valueForKey:DO_GROWL];
	
	if (doGrowl != nil && ![doGrowl boolValue])
		return;
		
	NSDictionary * userInfo = [note userInfo];

	BOOL update = NO;
	
	NSString * key = [userInfo valueForKey:KEY];
	NSObject * value = [userInfo valueForKey:PREDICTION];

	if (key == nil || value == nil)
		return;
		
	if (![value isEqual:[cache valueForKey:key]])
	{
		[cache setValue:value forKey:key];
		update = YES;
	}
		
	NSString * desc = [NSString stringWithFormat:@"New %@: %@\n", key, value];

	if (update)
	{
		if ([key isEqual:@"Activity"])
			[GrowlApplicationBridge notifyWithTitle:ACTIVITY_UPDATE description:desc notificationName:ACTIVITY_UPDATE
										   iconData:nil priority:0 isSticky:NO	clickContext:nil];
		else if ([key isEqual:@"Location"])
			[GrowlApplicationBridge notifyWithTitle:LOCATION_UPDATE description:desc notificationName:LOCATION_UPDATE
										   iconData:nil priority:0 isSticky:NO	clickContext:nil];
		else if ([key isEqual:@"Social Context"])
			[GrowlApplicationBridge notifyWithTitle:SOCIAL_UPDATE description:desc notificationName:SOCIAL_UPDATE
										   iconData:nil priority:0 isSticky:NO	clickContext:nil];
		else
			[GrowlApplicationBridge notifyWithTitle:CONTEXT_UPDATE description:desc notificationName:CONTEXT_UPDATE
										   iconData:nil priority:0 isSticky:NO	clickContext:nil];
	}
}

@end
